// pages/goods/shop-cart.js
const numeral = require("../../vendor/numeral/numeral.min")
const app = getApp()
Page({

    data: {
        startX: 0, //开始坐标
        startY: 0
    },

    onLoad: function() {
        this.loadCart()
    },
    loadCart() {
        let {
            cartNum = 0, totalPrice = 0,
        } = this.data
        let cid = wx.getStorageSync('cid')
        if (!cid) return
        wx.showLoading({
            title: '加载中...',
        })
        app.http.post('shopping-cart/list-shopping-cart', {
            data: {
                cid: cid,
            }
        }).then(res => {
            let list = [],
                disableList = []
            res.data.forEach(o => {
                let startime = Date.parse(new Date()) / 1000;
                o.isTouchMove = false
                if (parseInt(o.end_at) - startime > 0) {
                    list.push(o)
                } else {
                    disableList.push(o)
                }
                return o
            })
            this.setData({
                list,
                disableList,
                checkAll: false,
            })
            this.calculateTotal()
            wx.stopPullDownRefresh()
            wx.hideLoading()
        })
    },
    /**
     * 计算商品总数
     */
    calculateTotal: function() {
        let list = this.data.list;
        let totalCount = 0;
        let totalPrice = 0;
        let cartNum = 0;

        if (!list) {
            return
        }
        for (let i = 0; i < list.length; i++) {
            var good = list[i];
            cartNum += parseInt(good.quantity);
            if (good.checked) {
                totalCount += parseInt(good.quantity);
                totalPrice += parseInt(good.quantity) * (good.mallPrice - 0);
            }
        }
        totalPrice = numeral(totalPrice).format("0,0.00")
        this.setData({
            totalCount,
            totalPrice,
            cartNum
        })
    },
    /**
     * 修改数量
     */
    numClick(evt) {
        let dset = evt.currentTarget.dataset;
        let {
            index,
            step
        } = dset
        let list = this.data.list
        let cartid = list[index].cart_id
        let quantity = parseInt(list[index].quantity)
        if (this.data.updating) return

        quantity = quantity + parseInt(step)

        if (quantity < 1) {
            wx.showToast({
                icon: 'none',
                title: '宝贝不能再减少啦~',
            })
            return
        }
        if (quantity > list[index].stock) {
            wx.showToast({
                icon: 'none',
                title: '库存不足啦~',
            })
            return
        }
        if (quantity > list[index].max_buy_num && list[index].max_buy_num != 0) {
            wx.showToast({
                icon: 'none',
                title: '宝贝已到达最大购买数~',
            })
            return
        }
        this.setData({
            updating: true,
            [`list[${index}].quantity`]: quantity,
        })
        this.calculateTotal()
        this.updateCartNum(cartid, step, index)
    },
    /**
     * 修改购物车数量
     */
    updateCartNum(cartid, step, index) {
        if (!cartid) return
        app.http.post('shopping-cart/update-shopping-cart', {
            data: {
                cart_id: cartid,
                "type": step == 1 ? 1 : 2
            }
        }).then(res => {
            if (res.data.status == 1) {
                this.setData({
                    updating: false,
                    [`list[${index}].quantity`]: res.data.quantity,
                })
            } else {
                wx.showModal({
                    title: '提示',
                    content: res.data.msg,
                    showCancel: false
                })
            }
        })
    },
    /**
     * 多项选择
     */
    checkboxChange: function(e) {
        var list = this.data.list,
            values = e.detail.value,
            checkAll = !this.data.checkAll,
            k = 0

        for (var i = 0; i < list.length; ++i) {
            list[i].checked = false;
            for (var j = 0; j < values.length; ++j) {
                if (list[i].cart_id == values[j]) {
                    list[i].checked = true;
                    k++
                    break;
                }
            }
            checkAll = k == list.length
        }
        this.setData({
            list,
            checkAll,
        });
        this.calculateTotal()
    },

    /**
     * 全选
     */
    selectalltap: function(e) {
        let checkAll = this.data.checkAll;
        checkAll = !checkAll
        let list = this.data.list

        for (let i = 0; i < list.length; i++) {
            list[i].checked = checkAll
        }

        this.setData({
            list,
            checkAll
        })
        this.calculateTotal();
    },

    onPullDownRefresh: function() {
        this.loadCart()
    },

    //手指触摸动作开始 记录起点X坐标
    touchstart: function(e) {
        this.setData({
            startX: e.changedTouches[0].clientX,
            startY: e.changedTouches[0].clientY,
        })
    },
    //滑动事件处理
    touchmove: function(e) {
        var index = e.currentTarget.dataset.index,
            ltype = e.currentTarget.dataset.type,
            startX = this.data.startX, //开始X坐标
            startY = this.data.startY, //开始Y坐标
            touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
            touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
            arr = ltype == 1 ? this.data.list : this.data.disableList,
            //获取滑动角度
            angle = this.angle({
                X: startX,
                Y: startY
            }, {
                X: touchMoveX,
                Y: touchMoveY
            });
        arr.forEach((v, i) => {
            v.isTouchMove = false
            //滑动超过30度角 return
            if (Math.abs(angle) > 10) return;
            if (i == index) {
                if (touchMoveX > startX) //右滑
                    v.isTouchMove = false
                else //左滑
                    v.isTouchMove = true
            }
        })
        //更新数据
        if (ltype == 1) {
            this.setData({
                list: arr
            })
        } else {
            this.setData({
                disableList: arr
            })
        }
    },
    /**
     * 计算滑动角度
     * @param {Object} start 起点坐标
     * @param {Object} end 终点坐标
     */
    angle: function(start, end) {
        var _X = end.X - start.X,
            _Y = end.Y - start.Y
        //返回角度 /Math.atan()返回数字的反正切值
        return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
    },
    del: function(e) {
        let index = e.currentTarget.dataset.index
        let ltype = e.currentTarget.dataset.type
        let arr = ltype == 1 ? this.data.list : this.data.disableList
        app.http.post('shopping-cart/delete-shopping-cart', {
            data: {
                cart_id_group: arr[index].cart_id,
            }
        }).then(res => {
            if (res.data.status == 1) {
                arr.splice(index, 1)
            }
            if (ltype == 1) {
                this.setData({
                    list: arr
                })
            } else {
                this.setData({
                    disableList: arr
                })
            }
        })

    }
})